package com.greenant.store.activity;

import java.io.IOException;
import java.util.Vector;

import com.avos.avoscloud.AVUser;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;
import com.greenant.store.AntHomeApplication;
import com.greenant.store.R;
import com.greenant.store.bean.AntGoodsBase;
import com.greenant.store.camera.CameraManager;
import com.greenant.store.decoding.CaptureActivityHandler;
import com.greenant.store.decoding.InactivityTimer;
import com.greenant.store.service.RetrieveDataAsyn;
import com.greenant.store.service.RetrieveDataListener;
import com.greenant.store.utils.UtilTools;
import com.greenant.store.utils.iLog;
import com.greenant.store.view.AddGoodsOnLineDialog;
import com.greenant.store.view.SingleChooseDialog;
import com.greenant.store.view.ViewfinderView;
import com.lsarah.utils.SystemBarTintManager;

import android.app.ActionBar;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

public class CaptureActivity extends BaseActivity implements Callback {

	private CaptureActivityHandler handler;
	private ViewfinderView viewfinderView;
	private boolean hasSurface;
	private Vector<BarcodeFormat> decodeFormats;
	private String characterSet;
	private InactivityTimer inactivityTimer;
	private MediaPlayer mediaPlayer;
	private boolean playBeep;
	private static final float BEEP_VOLUME = 0.10f;
	private boolean vibrate;

	
	//�豸���ͣ�5350����4004.
	//5303����Ҫһ�����ã�4004��Ҫһ������
	private int gatewayType = 4004;
	
	
	private TextView titleView;
	private ImageView rightIcon;
	private ImageView leftIcon;
	
	private ProgressBar progressBar;

	private final static String TAG_SWITCH = "TAG_SWITCH";
	private final static String TAG_BACK = "TAG_BACK";
	
	private Context mContext;
	
	/**
	 * 扫描返回结果
	 */
	public static int CAPTURE_RESULT_OK=RESULT_OK;
	public static int CAPTURE_RESULT_CANCELED=RESULT_CANCELED;
	public static int CAPTURE_RESULT_CODE=2;
	/**
	 * 扫描结果返回的key
	 * 
	 */
	public static String KEY_CAPTURE_CODE="key_CAPTURE_CODE";
	public static String KEY_CAPTURE_BEAN="key_CAPTURE_BEAN";
	public static String KEY_CAPTURE_TYPE="KEY_CAPTURE_TYPE";
	
	public final static int CAPTURE_TYPE_GOODS=0;
	public final static int CAPTURE_TYPE_EMRECV=1;
	
	//扫描类型
	private  int captureType=CAPTURE_TYPE_GOODS;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		SystemBarTintManager.setContentView(this,
				R.layout.activity_capture,
				getResources().getColor(R.color.firebrick));
		mContext=this;
		// ��ʼ�� CameraManager
		CameraManager.init(getApplication());
		viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
		progressBar=(ProgressBar)findViewById(R.id.progressBar);
		hasSurface = false;
		inactivityTimer = new InactivityTimer(this);
		Intent intent = getIntent();
		if (intent != null) {
			gatewayType = intent.getIntExtra("gatewayType", 4004);//��ȡ�������
			captureType= intent.getIntExtra(KEY_CAPTURE_TYPE, CAPTURE_TYPE_GOODS);//��ȡ�������
		}
		setActionBarLayout(R.layout.actionbar);
		final EditText qrcode=(EditText)findViewById(R.id.qrcode);
		Button inputmanul=(Button)findViewById(R.id.inputmanul);
		inputmanul.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				if(!TextUtils.isEmpty(qrcode.getText().toString()))
				{
					processQRResult(qrcode.getText().toString());
				}
				
				
			}
		});
		
		this.findViewById(R.id.flashlight).setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				v.setSelected(!v.isSelected());
				boolean isLightOn = v.isSelected();
				iLog.d("isLightOn:"+isLightOn);
				CameraManager.get().setFlashLightOn(isLightOn);
				closeCamera();
				openCamera();
			}
		});
		if(captureType==CAPTURE_TYPE_EMRECV)
		{
			TextView title=(TextView)this.findViewById(R.id.capture_actionbar_title);
			title.setText(R.string.emrecv_capture_title);
		}
		
	}

	
	public void setActionBarLayout(int layoutId) {

		ActionBar actionBar = getActionBar();

		if (null != actionBar) {

			actionBar.setDisplayShowHomeEnabled(false);

			actionBar.setDisplayShowCustomEnabled(true);

			LayoutInflater inflator = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

			View v = inflator.inflate(layoutId, null);

			ActionBar.LayoutParams layout = new ActionBar.LayoutParams(LayoutParams.FILL_PARENT,
					LayoutParams.FILL_PARENT);

			actionBar.setCustomView(v, layout);
			titleView = (TextView) v.findViewById(R.id.title);
			titleView.setText(this.getString(R.string.capture_device_scan_register));


		
		}

	}
	

	private void setLeftIconType(String type) {

		if (TAG_SWITCH.equals(type)) {
			leftIcon.setTag(TAG_SWITCH);
		} else if (TAG_BACK.equals(type)) {
			leftIcon.setTag(TAG_BACK);
		}

	}
	
	@Override
	protected void onResume() {
		super.onResume();
		openCamera();
	}
	
	private void openCamera(){
		SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
		SurfaceHolder surfaceHolder = surfaceView.getHolder();
		if (hasSurface) {
			initCamera(surfaceHolder);
		} else {
			surfaceHolder.addCallback(this);
			surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		}
		decodeFormats = null;
		characterSet = null;

		playBeep = true;
		AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
		if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
			playBeep = false;
		}
		initBeepSound();
		vibrate = true;
	}

	@Override
	protected void onPause() {
		super.onPause();
		closeCamera();
	}

	private void closeCamera(){
		if (handler != null) {
			handler.quitSynchronously();
			handler = null;
		}
		CameraManager.get().closeDriver();	
	}
	
	@Override
	protected void onDestroy() {
		inactivityTimer.shutdown();
		super.onDestroy();
	}

	private void initCamera(SurfaceHolder surfaceHolder) {
		try {
			CameraManager.get().openDriver(surfaceHolder);
		} catch (IOException ioe) {
			return;
		} catch (RuntimeException e) {
			return;
		}
		if (handler == null) {
			handler = new CaptureActivityHandler(this, decodeFormats, characterSet);
		}
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		if (!hasSurface) {
			hasSurface = true;
			initCamera(holder);
		}

	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		hasSurface = false;

	}

	public ViewfinderView getViewfinderView() {
		return viewfinderView;
	}

	public Handler getHandler() {
		return handler;
	}

	public void drawViewfinder() {
		viewfinderView.drawViewfinder();

	}

	public void handleDecode(final Result obj, Bitmap barcode) {
		inactivityTimer.onActivity();
		playBeepSoundAndVibrate();

		inactivityTimer.onActivity();
		playBeepSoundAndVibrate();
		String resultString = obj.getText();
		processQRResult(resultString);
	
	}
	
	
	private void processQRResult(String result) {
		if (!TextUtils.isEmpty(result)) {
			result = result.toUpperCase();
		}
		iLog.d("KEY_serialNumber��" + result);
		final String resultCode = result;

		if (captureType == CAPTURE_TYPE_GOODS) {
			progressBar.setVisibility(View.VISIBLE);
			RetrieveDataAsyn.getInstance().checkIfGoodsOnline(resultCode, 0, new RetrieveDataListener() {

				@Override
				public void dataRetrieved(int requestId, final Object data) {
					progressBar.setVisibility(View.INVISIBLE);
					if (data == null) {
						SingleChooseDialog dialog = new SingleChooseDialog(mContext, resultCode);
						String[] s = { mContext.getString(R.string.capture_hint_nogoods) };
						dialog.addItems(s);
						dialog.show();
						dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {

							@Override
							public void onDismiss(DialogInterface dialog) {
								// 实现连续扫描
								handler.sendEmptyMessage(R.id.restart_preview);
							}
						});
					} else {

						AVUser user = AVUser.getCurrentUser();
						if (user != null) {
							RetrieveDataAsyn.getInstance().checkIfGoodsAlreadyAdded(resultCode, user.getObjectId(),
									requestId, new RetrieveDataListener() {

								@Override
								public void dataRetrieved(int requestId, Object goodsData) {
									if (goodsData == null) {
										AntGoodsBase antGoodsBase = (AntGoodsBase) data;
										new AddGoodsOnLineDialog(mContext, antGoodsBase,
												AntHomeApplication.sCurrentStoreInfo, null).show();
									} else {
										UtilTools.showMyToast(mContext,
												mContext.getString(R.string.capture_hint_hasgoods));
										handler.sendEmptyMessage(R.id.restart_preview);
									}
								}
							});
						} else {
							UtilTools.isUserLogined(mContext);
						}

					}

				}
			});
		} else {
			Intent intent = getIntent();
			if (intent == null) {
				intent = new Intent();
			}
			intent.putExtra(KEY_CAPTURE_CODE, resultCode);
			setResult(RESULT_OK, intent);
			finish();
		}

	}
	public void goBack(View view) {
		Intent intent=new Intent();
		setResult(RESULT_CANCELED, intent);
		finish();
	}
	private void initBeepSound() {
		if (playBeep && mediaPlayer == null) {
			// The volume on STREAM_SYSTEM is not adjustable, and users found it
			// too loud,
			// so we now play on the music stream.
			setVolumeControlStream(AudioManager.STREAM_MUSIC);
			mediaPlayer = new MediaPlayer();
			mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
			mediaPlayer.setOnCompletionListener(beepListener);

			AssetFileDescriptor file = getResources().openRawResourceFd(R.raw.beep);
			try {
				mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength());
				file.close();
				mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
				mediaPlayer.prepare();
			} catch (IOException e) {
				mediaPlayer = null;
			}
		}
	}

	private static final long VIBRATE_DURATION = 200L;

	private void playBeepSoundAndVibrate() {
		if (playBeep && mediaPlayer != null) {
			mediaPlayer.start();
		}
		if (vibrate) {
			Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
			vibrator.vibrate(VIBRATE_DURATION);
		}
	}

	/**
	 * When the beep has finished playing, rewind to queue up another one.
	 */
	private final OnCompletionListener beepListener = new OnCompletionListener() {
		public void onCompletion(MediaPlayer mediaPlayer) {
			mediaPlayer.seekTo(0);
		}
	};


}